//
//  AutoLoginOperation.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-25.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
//用于自动登陆
#import "AutoLoginOperation.h"
#import "URLFactory.h"
#import "CoreDataManager.h"
#import "LFAccount.h"
#import "ASIHTTPRequest.h"
#import "JSON.h"
#import "CONSTS.h"


@interface AutoLoginOperation()

- (void)autoIsEnd;
- (void)autoIsSuccess;
- (void)autoIsFail;
- (void)saveUserInfo;

@end


@implementation AutoLoginOperation

@synthesize delegate = _delegate;

- (void)dealloc
{
    [_resultDic release];
    _resultDic = nil;
    
    [super dealloc];
}

- (id)initByD:(id<AutoLoginDelegate>)delegate_
{
    self = [super init];
    if (self)
    {
        self.delegate = delegate_;
    }
    
    return self;
}

- (void)main
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    CoreDataManager *coreDataManager = [CoreDataManager sharedCoreDataManager];
    LFAccount *account = [coreDataManager getCurrentLoggedInAccount];
    NSString *token = account.token;
    
    if (!token) //如果本地没有存有token说明自动会失败,这个类只关系登陆失败的成功和失败，至于为什么失败，这个类并不关心
    {
        [self autoIsFail];
        
        return;
    }
    
    NSString *com_taobao_client_sys_autologin_str = [URLFactory get_com_taobao_client_sys_autologin];
    NSURL *autoUrl = [NSURL URLWithString: com_taobao_client_sys_autologin_str];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: autoUrl];
    [request startSynchronous];
    
    if (request.error)  //如果网络连接出现错误
    {
        [self autoIsFail];
        
        return;
    }
    
    _resultDic = [[request.responseString JSONValue] retain];
    if (!_resultDic || [_resultDic count] <= 0) //如果返回值为空或者...
    {
        [self autoIsFail];
        
        return;
    }
    
    //以上检测，说明taobao服务器已经返回了json
    [self autoIsEnd];
    
    [pool release];
}


- (void)autoIsEnd
{
    /*
     {"api":"com.taobao.client.sys.autologin","v":"2.0","ret":["SUCCESS::调用成功"],"data":{"sid":"4edc0e786dac5c37e7e8fa334c2b7bbd","ecode":"enNtN","nick":"wdch999","logintime":"1322203204","userId":"22942843"}}
     */
    if (!_resultDic || [_resultDic count] <= 0 || !([[[_resultDic objectForKey: @"ret"] objectAtIndex: 0] isEqualToString: AUTO_LOGIN_SUCCESS_SIGN]))
    {
        [self autoIsFail];
    }else
    {
        [self autoIsSuccess];
    }
}

- (void)autoIsSuccess
{
    if (_delegate && [_delegate respondsToSelector: @selector(autoLoginSuccess:)])
    {
        [((NSObject *)self.delegate) performSelectorOnMainThread: @selector(autoLoginSuccess:) 
                                                      withObject: _resultDic 
                                                   waitUntilDone: NO];
        [self saveUserInfo];
    }
}

- (void)autoIsFail
{
    if (_delegate && [_delegate respondsToSelector: @selector(autologinFail:)])
    {
        [((NSObject *)self.delegate) performSelectorOnMainThread: @selector(autologinFail:) 
                                                      withObject: _resultDic 
                                                   waitUntilDone: NO];
    }
}

- (void)saveUserInfo    // 将返回的用户的登陆数据放入coreData
{
    /*
     {"api":"com.taobao.client.sys.autologin","v":"2.0","ret":["SUCCESS::调用成功"],"data":{"sid":"4edc0e786dac5c37e7e8fa334c2b7bbd","ecode":"enNtN","nick":"wdch999","logintime":"1322203204","userId":"22942843"}}
     */
    
#ifdef DEBUG
    writeJsonToPlist( _resultDic, api_com_taobao_client_sys_autologin);
#endif
    
    ITTDINFO(@"%@", _resultDic);
    
    CoreDataManager *coreDataManager = [CoreDataManager sharedCoreDataManager];
    LFAccount *account = [coreDataManager getCurrentLoggedInAccount];
    
    NSDictionary *dataDic = [_resultDic objectForKey: @"data"];
    
    NSString *sid = [dataDic objectForKey: @"sid"];
    ITTDINFO(@"获取之前：%@", account.sid);
    account.sid = sid;
    ITTDINFO(@"获取之后 sid = ：%@", account.sid);
    
    NSString *ecode = [dataDic objectForKey: @"ecode"];
    account.ecode = ecode;
    
    NSString *nick = [dataDic objectForKey: @"nick"];
    account.nick = nick;
    
    [coreDataManager saveChangesToCoreData];
}

@end

